<?php
/**
 * 卡片产品逻辑层
 * User: Acer
 * Date: 2022/7/9
 * Time: 2:23
 */
namespace app\card\service;

use app\admin\models\UserModel;
use app\admin\models\LoggerModel;
use app\admin\service\UserServide;
use app\card\models\CardModel;
use app\card\models\CardProModel;
use app\card\models\UserCardModel;
use app\move\models\FamilyCardModel;
use app\move\models\IdentityCardModel;
use think\Db;

class CardProService
{
    protected $code_number = 0;
    /**
     *
     * 产生随机字符串，不长于32位
     * @param int $length
     * @return 产生的随机字符串(不含4和7)
     */
   protected function getNonceStrCard($length = 32)
    {
        $chars = "AabBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ01235689";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }



    //設置卡片激活碼
    
public function makeCardPassword (){
     $password = '';
    $characters = '123456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ';
    $length = strlen($characters);
    for ($i = 0; $i < 9; $i++) {
        $password .= $characters[rand(0, $length - 1)];
    }
    return $password;
}


    protected function crdeCodePas(){
        $CardProModel = new CardProModel();
        // 查看卡号密码是否存在
       // $card_Pas = makeCardPassword();
        $card_Pas = $this->makeCardPassword();
        $card = $CardProModel->where('password',$card_Pas)->value('pid');
        if(!$card) {
            return $card_Pas;
        }else{
            if($this->code_number > 6){
                $this->code_number = 0;
                return false;
            }else{
                $this->code_number = $this->code_number + 1;
                $this->crdeCodePas();
            }
        }
    }

    // 批量创建卡片产品
    public function s_add_card_pro($data,$c_uid){
        if(!isset($data['number']) && (int)$data['number'] <= 0) return false;
//        if((int)$data['number'] > 2000) json_err(-210,['最大批量创建数为：2000']);
        // 根据cid获取卡片信息
        $cardInfo =  (new CardService())->getCardInfo($data['cid']);
        // 根据卡片信息获取前缀、后缀和中间数，是否有存在相同的设置，这里必须保持唯一
        $cardSet = (new CardService())->getCardCodeNumber($cardInfo['prefix'],$cardInfo['middle'],$cardInfo['suffix'],$data['cid']);
       // if($cardSet) json_err(-210,['存在相同卡片编号的设置，请更改卡片编号设置并保证唯一性！']);
        
        
        $CardProModel = new CardProModel();
        Db::startTrans();
        $len = (int)$data['number'];
        for ($i=0; $i<=$len; $i++)
        {
            $data =[
                'cid'       =>  $data['cid'],               // 卡片id
                'password'  =>  $this->crdeCodePas(),         // 卡片密码
                'state'     =>  1,
                'c_uid'     =>  $c_uid, // 卡片创建用户id
            ];
           $resId = $CardProModel->insertGetId($data);
            if(!$resId) {  // 失败
                Db::rollback(); // 回滚事务
                json_err(205);
                exit();
            }else{
                // 根据之前同类型中，最大的卡片code，然后进行叠加
               $maxInfo = (int)$CardProModel->where('cid',$data['cid'])->max('pid');
    
   //   $sql ="SELECT MAX(`code`) FROM card_product where cid ='4'";

    //执行插入操作
   // $maxInfo = Db::execute($sql);  
    
    
                print_r($maxInfo);
           
                
                if($maxInfo){
                    // 存在最大code编号
                    // 截取中间值，去掉前后缀的数字
                    $middle =substr($maxInfo,strlen($cardInfo['prefix']),$cardInfo['middle']);
                    
                    echo($middle);
                    $code_middle = sprintf('%0'.$cardInfo['middle'].'s', (int)$middle + 1);
                    $code = $cardInfo['prefix'].$code_middle.$cardInfo['suffix'];
                }else{
              
                    // 不存在最大code编号，则按照卡片设置进行组装生成
                    $code = $cardInfo['prefix'].sprintf('%0'.$cardInfo['middle'].'s', $maxInfo + 1).$cardInfo['suffix']; // 卡片code
                }
                $res = $CardProModel->save([
                    'code'  =>  $code,
                    'card_no'  =>  $maxInfo+1,
                ],[
                    'pid'   =>  $resId
                ]);
                if($res){
                    if($len == $i + 1) {
                        Db::commit();
                        return true;
                    }
                } else{
                    Db::rollback(); // 回滚事务
                    json_err(205);
                    return false;
                }
            }
        }
    }
    // 获取卡片产品信息
    public function m_card_pro_info($pid){
        return (new CardProModel())->where('pid',$pid)->find();
    }

    // 修改卡片产品状态
    public function s_state_card_pro($data){
        if(isset($data['pid'])){
            // 是否存在产品信息
            $card_info = $this->m_card_pro_info($data['pid']);
            $card_info = obj_to_arr($card_info);
            if(!$card_info) json_err(-204,['卡片产品信息，']);
            $res =  (new CardProModel())->save([
                'state'     =>  $card_info['state'] == 1 ? 0 : 1,
            ],[
                'pid' =>$data['pid']
            ]);
            return $res;
        }
        return false;
    }

    // 获取列表
    public function  s_card_pro_list($page,$paginate=10,$like){
        $CardProModel = new CardProModel();
        $CardProModel->alias("cp")->field("cp.*")->join('user_card uc', 'cp.pid=uc.pid', 'LEFT');
        // 卡片产品code
        if(isset($like['code'])){
            $CardProModel->whereLike('cp.code',$like['code'].'%');
        }
        // 卡片产品code
        if(isset($like['cid'])){
            $CardProModel->where('cp.cid',$like['cid']);
        }
        // ActiveVaue ： 1 已激活，2未激活
        if(isset($like['ActiveVaue'])){
            if($like['ActiveVaue']==1){
                $CardProModel->whereNotNull('uc.is_active');
            }else if($like['ActiveVaue']==2){
                $CardProModel->whereNull('uc.is_active');
            }
        }
        // T123123~T23121321
        if(isset($like['codeRange'])&&!empty($like['codeRange'])){
            if(strpos($like['codeRange'], '~') !== false){
                $codeRange=explode('~',$like['codeRange']);
                $CardProModel->where('cp.code','>=',$codeRange[0]);
                $CardProModel->where('cp.code','<=',$codeRange[1]);
            }else{
                $CardProModel->where('cp.code','>=',$like['codeRange']);
            }
        }
        $list = $CardProModel->order('cp.code')->paginate((int)$paginate,false,['page'=>$page])->each(function($item, $key){
            // 获取卡片绑定信息
            $card_user = (new UserCardModel())->where(['pid'=>$item['pid']])->find();
            $card_user = obj_to_arr($card_user);
            $item->card_user=(object)[];
            if(!$card_user){
                $item->card_user->is_active = 0;
            } else{
                $item->card_user = $card_user;
            }
            $item->card = obj_to_arr((new CardModel())->where(['cid'=>$item['cid']])->find());
        });
        return $list;
    }

    // 导出卡片产品
    public function s_export_card_pro($like,$cid){
        $CardProModel = new CardProModel();
        $CardProModel->alias("cp")->join('user_card uc', 'cp.pid=uc.pid', 'LEFT')
        ->join('identity_card ic', 'uc.uid=ic.uid', 'LEFT')
        ->field('cp.code,cp.password,cp.state,uc.is_active,uc.valid_time,ic.name,ic.mobile,ic.id_card,uc.manager_phone');
        // 卡片产品code
        if(isset($like['code'])){
            $CardProModel->whereLike('cp.code','%'.$like['code']);
        }
        // 产品类型
        if($cid){
            $CardProModel->where('cp.cid',$cid);
        }
        // ActiveVaue ： 1 已激活，2未激活
        if(isset($like['ActiveVaue'])){
            if($like['ActiveVaue']==1){
                $CardProModel->whereNotNull('uc.is_active');
            }else if($like['ActiveVaue']==2){
                $CardProModel->whereNull('uc.is_active');
            }
        }
        $list = $CardProModel->select();
        foreach ($list as $key => $value) {
            if ($value['state'] == 1) {
                $list[$key]['state']="启用";
            }else{
                $list[$key]['state']="禁用";
            }
            if(is_null($value['is_active'])){
                $list[$key]['is_active']="未激活";
            }else{
                $list[$key]['is_active']="已激活";
            }
            if(is_null($value['valid_time'])){
                $list[$key]['valid_time']="";
            }else{
                $list[$key]['valid_time']=date("Y-m-d H:i:s", $value['valid_time']);
            }
        }
        return obj_to_arr($list);
    }

    // 根据卡片id，获取卡片使用成员信息
    public function s_get_card_users($pid){
        // 主卡人信息
        $UserCardModel = new UserCardModel();
        $IdentityCardModel = new IdentityCardModel();
        $UserServide = new UserServide();
     
        $UserCardInfo = $UserCardModel->alias("a")->where('a.pid',$pid)->join("user b","b.id = a.uid")->join("identity_card c","c.uid = a.uid")->find();
      
        // 成员
        $FamilyCardModel = new FamilyCardModel();
        $FamilyCard = $FamilyCardModel->where('pid',$pid)->order('creation_time','asc')->select();
        $FamilyCard2 = $FamilyCardModel->where('pid',$pid)->where('type',999)->order('creation_time','asc')->select();
        if($FamilyCard){
            foreach($FamilyCard as $key=>$value){
                // 根据did获取用户认证信息
                $IdentityCardInfo = $IdentityCardModel->where('did',$value->did)->find();
                $IdentityCardInfo = obj_to_arr($IdentityCardInfo);
                $FamilyCard[$key]['identity_card_info'] = $IdentityCardInfo;
                $FamilyCard[$key]['user_info'] = (object)[];
                // 获取uid信息
                if($IdentityCardInfo['uid']) {
                    $FamilyCard[$key]['user_info'] =  $UserServide->s_get_user_info($IdentityCardInfo['uid']);
                }
                if($FamilyCard2){
                    $FamilyCard[$key]['equityer'] = '主权益人';
                }else{
                    $FamilyCard[$key]['equityer'] = '副权益人'.($key+1);
                }
            }
        }

        if( $FamilyCard2){
            if($UserCardInfo) {
                $UserCardInfo['equityer'] = '代激活人';
            }
            return [
                'card_user_info'    =>  $UserCardInfo, // 主卡
                'card_member_info'  =>  $FamilyCard // 成员卡信息
            ];
            
        }else{
            if($UserCardInfo) {
                $UserCardInfo['equityer'] = '主权益人';
            }
            return [
                'card_user_info'    =>  $UserCardInfo, // 主卡人信息
                'card_member_info'  =>  $FamilyCard // 成员卡信息
            ];
        }
    }

    // 查询pid、did进行绑定的数据[主卡人]
    public function s_get_card_bind_user($pid,$did){
        // 根did，获取uid
        $IdentityCardModel = new IdentityCardModel();
        $uid =  $IdentityCardModel->where('did',$did)->value("uid");
        if(!$uid) json_err(-204,['成员实名信息，']);
        $UserCardModel =  new UserCardModel();
        $userCardInfo = $UserCardModel->where('pid',$pid)->where('uid',$uid)->find();
        if(!$userCardInfo ) json_err(-204,['绑定卡片信息，']);
        return $userCardInfo;
    }
    // 查询pid、uid进行绑定的数据[家庭成员]
    public function s_get_card_bind_user_member($pid,$did){
          $FamilyCardModel = new FamilyCardModel();
          $userCardInfo = $FamilyCardModel->where('pid',$pid)->where('did',$did)->find();
          if(!$userCardInfo) json_err(-204,['绑定卡片成员信息，']);
          return $userCardInfo;
    }

    // 解绑卡片
    public function s_card_pro_unbound($pid,$type,$did){
        // 查询是否存在pid、uid进行绑定的数据
        if((int)$type == 1){ // 解绑主卡人，则会取消旗下所有成员
            $UserCardModel =  new UserCardModel();
            // 查询
            $userCardInfo = $this->s_get_card_bind_user($pid,$did);
            // 解绑
            Db::startTrans();
            try {
                $userCardInfo = obj_to_arr($userCardInfo);
                $res  = $UserCardModel->where('pid',$pid)->where('uid',$userCardInfo['uid'])->delete();
                // 解绑成员卡
                if($res){
                    $FamilyCardModel = new FamilyCardModel();
                    $FamilyCardModel->where('pid',$pid)->where('puid',$userCardInfo['uid'])->delete();
                }
                return true;
            }catch(\Exception $e){
                //如获取到异常信息，对所有表的删、改、写操作，都会回滚至操作前的状态：
                Db::rollback();
                json_err(-210,[$e->getMessage()]);
            }
        }else if((int)$type == 2){ // 解绑主卡人的成员
            // 查询
            $this->s_get_card_bind_user_member($pid,$did);
            $FamilyCardModel = new FamilyCardModel();
            $res = $FamilyCardModel->where('pid',$pid)->where('did',$did)->delete();
            return $res;
        }
    }

    // 设置出库和归属地
    public function set_outbound($pid,$outbound,$region,$buyer,$uid){
        $CardProModel = new CardProModel();
        $data = ['outbound_time' => date("Y-m-d H:i:s", time())];
        $loggerContent = array();
        if(!empty($region)) {
            $data['region'] = $region;
            $loggerContent[] = "设置归属地：".$region;
        }
        if(!empty($buyer)){
            $data['buyer'] = $buyer;
            $loggerContent[] = "设置购卡人：".$buyer;
        }
        if($outbound!==null&&$outbound!==''){
            $data['outbound'] = $outbound;
            if($outbound=='1'){
                $loggerContent[] = "设置出库状态：出库";
            }
            if($outbound=='0'){
                $data['outbound_time'] = null;
                $data['region'] = null;
                $data['buyer'] = null;
                $loggerContent[] = "设置出库状态：未出库";
                $loggerContent[] = "设置归属地：空";
                $loggerContent[] = "设置购卡人：空";
            }
        }

        $creator = (new IdentityCardModel())->where('uid',$uid)->value('name');
        $LoggerModel = new LoggerModel();
        foreach (explode(',',$pid) as $value) {
            $LoggerModel->insert([
                "link_id"=>$value,
                "type"=>0,
                "content"=>json_encode($loggerContent),
                "creator"=>$creator
            ]);
        }
        return $CardProModel->where('pid','in',explode(',',$pid))->update($data);
    }

    // 设置出库和归属地
    public function set_notes($pid,$notes){
        $CardProModel = new CardProModel();
        $data = ['notes' => $notes];
        return $CardProModel->where('pid','in',explode(',',$pid))->update($data);
    }

    // 延迟出库
    public function delay_outbound($pid,$num,$uid){
        $CardProModel = new CardProModel();

        $creator = (new IdentityCardModel())->where('uid',$uid)->value('name');
        $loggerContent = array("设置延迟出库：$num 天");
        $LoggerModel = new LoggerModel();
        foreach (explode(',',$pid) as $value) {
            $LoggerModel->insert([
                "link_id"=>$value,
                "type"=>0,
                "content"=>json_encode($loggerContent),
                "creator"=>$creator
            ]);
        }

        return $CardProModel->where('pid','in',explode(',',$pid))
            ->update([
                'outbound_time' => Db::raw(sprintf('DATE_ADD(outbound_time, INTERVAL %s DAY)', $num))
            ]);
    }

    // 获取操作日志
    public function get_logger($page,$paginate=10,$linkId,$type){
        return obj_to_arr((new LoggerModel())->where([
            'link_id'=>$linkId,
            'type'=>$type,
        ])->order('creation_time','desc')->paginate((int)$paginate,false,['page'=>$page]));
    }
}
